package top.carrotguo.iteration;

/**
 * 求数组中最大数和次大数(迭代法)
 * @Author: Carrot
 * @Mail: 1053155183carrot@gmail.com
 * @Date: Created in 21:50 2018-05-13
 */
public class MaxTwo {

    public static void max2 (int[] A, int lo, int hi) {
        int x1 = lo;
        int x2 = lo+1;
        int temp;
        if (A[x1]<A[x2]) {      //x1指向最大数  x2指向次小数
            temp = x1;
            x1 = x2;
            x2 = temp;
        }
        for (int i=lo+2; i<hi; i++) {     //不包括hi
            if (A[x2]<A[i]) {
                x2 = i;          //因为它比次大数大 因此i暂时保存为次大数
                if (A[x1]<A[i]) {
                    x2 = x1;
                    x1 = i;
                }
            }
        }
        System.out.print("最大数："+A[x1]+",   次大数："+A[x2]);
    }

    public static void main (String[] args) {
        max2(new int[]{1,2,3,5,4},0,5);
    }

}
